package com.letoy.edu.service.Impl;

import com.letoy.edu.dao.StudentInfoMapper;
import com.letoy.edu.dao.TokenInfoMapper;
import com.letoy.edu.dao.UserMapper;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.entity.User;
import com.letoy.edu.service.ThirdPartService;
import com.letoy.edu.service.auth.AuthUser;
import com.letoy.edu.vo.Student;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ThirdPartServiceImpl implements ThirdPartService {

    @Resource
    StudentInfoMapper studentInfoMapper;

    @Resource
    TokenInfoMapper tokenInfoMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public AuthUser loginByTokenAndType(TokenInfo tokenInfo, String type, int studentNumber) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (studentNumber == 0) {
            TokenInfo resToken = tokenInfoMapper.getTokenByTokenInfo(tokenInfo);
            if (resToken == null) {
                //登录失败token不存在
                return null;
            } else {
                User user = userMapper.getUserByUserId(resToken.getUserId());
                authorities.add(new SimpleGrantedAuthority(user.getRoles()));
                return new AuthUser(user.getEmail(), user.getName(), resToken.getSystemToken(), user.getUserId(), user.getPassword(), 0, authorities);
            }
        } else {
            System.out.println("开始注册");
            Student student = studentInfoMapper.findStudentByNumber(studentNumber);
            tokenInfo.setUserId(student.getUserId());
            System.out.println(tokenInfo.toString());
            tokenInfoMapper.updateTokenInfoByUserId(tokenInfo);
            User user = userMapper.getUserByUserId(student.getUserId());
            TokenInfo resToken = tokenInfoMapper.getTokenByUserId(user.getUserId());
            authorities.add(new SimpleGrantedAuthority(user.getRoles()));
            return new AuthUser(user.getEmail(), user.getName(), resToken.getSystemToken(), user.getUserId(), user.getPassword(), 0, authorities);
        }

    }

}
